package com.browser.download;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class DownloadManager {
    private static final Logger logger = LoggerFactory.getLogger(DownloadManager.class);
    private final List<DownloadTask> downloads;
    private final ExecutorService executor;

    public DownloadManager() {
        this.downloads = new ArrayList<>();
        this.executor = Executors.newFixedThreadPool(3);
    }

    public void download(String url, String targetPath) {
        logger.info("Starting download from: {} to: {}", url, targetPath);
        DownloadTask task = new DownloadTask(url, targetPath);
        downloads.add(task);
        executor.submit(task);
    }

    public List<DownloadTask> getDownloads() {
        return new ArrayList<>(downloads);
    }

    public void pauseDownload(String taskId) {
        getTaskById(taskId).ifPresent(DownloadTask::pause);
    }

    public void resumeDownload(String taskId) {
        getTaskById(taskId).ifPresent(DownloadTask::resume);
    }

    public void cancelDownload(String taskId) {
        getTaskById(taskId).ifPresent(DownloadTask::cancel);
    }

    private java.util.Optional<DownloadTask> getTaskById(String taskId) {
        return downloads.stream()
                .filter(task -> task.getId().equals(taskId))
                .findFirst();
    }

    public void shutdown() {
        executor.shutdown();
    }
} 